/**
 * Created at 15/11/25.
 * @Author Ling.
 * @Email i@zeroling.com
 */
"use strict";
const shua = require('./shua'),
    fs = require('fs');
const thread = parseInt(process.argv[2]) || 10; //并发数量

function checkExt(filename, ext) {
    let fileExtTmp, fileExt;
    try {
        fileExtTmp = filename.split('.');
        fileExt = fileExtTmp[fileExtTmp.length - 1];
    } catch (e) {
        return false
    }
    return ext == fileExt;
}
//处理数据
let accountFiles = fs.readdirSync('./accounts').filter(filename => checkExt(filename, 'js'));
let allAccounts = Array.prototype.concat.apply([], accountFiles.map(file => require('./accounts/' + file))).sort(n => Math.random() - 0.5);
let accountPagelets = [];
for (let i = 0; i < thread; accountPagelets[i++] = []);
allAccounts.forEach((a, i) => {
    accountPagelets[i % thread].push(a);
});


function run(accounts, cb) {
    (function _run(now, accounts) {
        let len = accounts.length;
        if (now != len) {
            //console.log(`开始刷${accounts[now]['email']}`);
            shua(accounts[now]).then(status => {
                _run(now + 1, accounts);
            }).catch(err => {
                _run(now + 1, accounts);
            });
        } else {
            return cb && cb();
        }
    })(0, accounts);
    return run;
}

//run
console.log(`开始${thread}线程刷票, 一共有${allAccounts.length}个账号! Ling.`);
let i = 0;
for (let accounts of accountPagelets) {
    run(accounts, em => {
        i++;
        console.log(`结束${i}个线程, 还有${thread - i}个正在运行`);
        if (i === thread) {
            process.exit(0);
        }
    });
}
